package com.vinhvt.effiport.algorithm.genetic.bio;

import java.math.BigDecimal;
import java.math.MathContext;


import com.vinhvt.effiport.algorithm.genetic.GAsParameters;
import com.vinhvt.effiport.util.Transform;

public class WeightGene extends Gene {
	
	/**
	 * Instantiates a new weight gene.
	 * 
	 * @param bits the bits that represent for the chromosome. 
	 */
	public WeightGene(boolean[] bits) {
		super(bits);
		this.setValue(decipher());
	}
	
	/**
	 * Instantiates a new weight gene.
	 * 
	 * @param num the value 
	 */
	public WeightGene(Number num) {
		super(num);
		this.setBits(cipher());
	}

	@Override
	public boolean[] cipher() {		
		int wbl = GAsParameters.WEIGHT_BITS_LENGTH;
		double weight = this.getValue().doubleValue();
		boolean result[] = new boolean[wbl];
		
		//cipher position
		double subjecter = weight;
				
		for(int i = wbl - 1; i > 0; i--) {
			double tmp = subjecter * 2;
			result[wbl - 1 - i] = (tmp >= 1 ? true : false);
			subjecter = (tmp >= 1) ? tmp - 1 : tmp; 
		}
		return result;
	}

	@Override
	public Number decipher() {
		double result = 0.0;	
		int wbl = GAsParameters.WEIGHT_BITS_LENGTH;
		
		int tmp = Transform.toDecimal(this.getBits()).intValue();
		result = tmp / (Math.pow(2, wbl) - 1);
		
		BigDecimal bd = new BigDecimal(result, new MathContext(2));
		result = bd.doubleValue();
		return result;
	}
}
